package com.example.exam1.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.exam1.entity.Book;
import com.example.exam1.service.BookService;
import com.example.exam1.util.ResponseUtils;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author wushuang
 * recorrected by Deepwind
 */
@WebServlet("/book/*")
public class BookController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        // 检查登录状态
        if (!isLogin(req, resp)) {
            return;
        }
        // 根据 uri 将内容分发给对应函数进行处理
        String uri = req.getRequestURI();
        // 通常在常量上调用 equals 方法以避免变量为 null 情况
        if ("/book/search".equals(uri)) {
            doSearch(req, resp);
        }
    }

    /**
     * 书籍搜索接口
     */
    private void doSearch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String number = req.getParameter("number");

        // 检查参数不存在和参数为空串（仅含空字符）情况
        if (number == null || number.trim().isEmpty()) {
            // 注意：像此处这种特别常用的返回错误信息可以将其包装为工具函数，减少代码量并提高可读性
            // 如：ResponseUtils.gen404Response(resp, "书本编号为空");
            // 此处为方便理解不作封装，后面均使用封装写法
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 404);
            jsonObject.put("msg", "书本编号为空");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
            return;
        }

        // 数据封装，并调用service层方法处理
        Book book = new Book();
        book.setNumber(number);
        Book newBook = new BookService().searchBook(book);

        if (newBook == null) {
            ResponseUtils.gen404Response(resp, "不存在这本书");
        } else {
            ResponseUtils.genSuccessResponse(resp, "检索成功", newBook);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");

        if (!isLogin(req, resp)) {
            return;
        }

        String uri = req.getRequestURI();
        switch (uri) {
            case "/book/insert" -> {
                doInsert(req, resp);
            }
            case "/book/del" -> {
                doDel(req, resp);
            }
            case "/book/update" -> {
                doUpdate(req, resp);
            }
            default -> {
            }
        }
    }

    /**
     * 书籍信息更新接口
     */
    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 参数检查
        String number = req.getParameter("number");
        String author = req.getParameter("author");
        String name = req.getParameter("name");
        if (number == null || author == null || name == null || name.trim().isEmpty() || author.trim().isEmpty() || number.trim().isEmpty()) {
            ResponseUtils.gen404Response(resp, "你所发送的数据不全");
            return;
        }

        // 数据封装，并调用service层方法处理
        int res = new BookService().updateBook(new Book(author, name, number));

        // 结果返回
        if (res == 0) {
            ResponseUtils.gen404Response(resp, "找不到编号为 " + number + " 的书");
        } else {
            ResponseUtils.genSuccessResponse(resp, "更新成功",null);
        }
    }

    /**
     * 书籍删除接口
     */
    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String number = req.getParameter("number");

        Book book = new Book();
        book.setNumber(number);
        int res = new BookService().delBook(book);

        if (res == 0) {
            ResponseUtils.gen404Response(resp, "找不到编号为 " + number + " 的书");
        } else {
            ResponseUtils.genSuccessResponse(resp, "删除成功", null);
        }
    }

    /*
     * 书籍插入接口
     */
    private void doInsert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (new BookService().fromCSV() == 0) {
            ResponseUtils.gen500Response(resp, "插入完成，部分书籍已存在");
        } else {
            ResponseUtils.genSuccessResponse(resp, "插入成功", null);
        }
    }

    /*
     * 登录状态检查函数
     */
    private boolean isLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (req.getSession().getAttribute("user") == null) {
            ResponseUtils.genBaseResponse(resp, 400, "请先登录", null);
            return false;
        }
        return true;
    }
}
